<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\LogoRequest;
use App\Models\Application\Logo;
use App\Repositories\Application\LogoRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;

class LogoController extends Controller
{
    use ModelForm;

    /** @var  LogoRepository */
    private $logoRepository;

    public function __construct(LogoRepository $logoRepo)
    {
        $this->logoRepository = $logoRepo;
    }

    /**
     * Display a listing of the Logo.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.logos.index_header'));
            $content->description(__('application.logos.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Logo.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.logos.create_header'));
            $content->description(__('application.logos.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Logo in storage.
     *
     * @param LogoRequest $request
     *
     * @return Response
     */
    public function store(LogoRequest $request)
    {
        $input = $request->all();

        // 单个页面只能对应单个布局
        $image = $request->file('href'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.logo');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['href'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $logo = $this->logoRepository->create($input);

        Flash::success(__('application.logos.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.logos.index'));

    }

    /**
     * Display the specified Logo.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $logo = $this->logoRepository->findWithoutFail($id);

        if (empty($logo)) {
            Flash::error(__('application.logos.not_found'));

            return redirect(route('application.logos.index'));
        }

        return view('application.logos.show')->with('logo', $logo);

    }

    /**
     * Show the form for editing the specified Logo.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('application.logos.edit_header'));
            $content->description(__('application.logos.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Logo in storage.
     *
     * @param  int              $id
     * @param LogoRequest $request
     *
     * @return Response
     */
    public function update($id, LogoRequest $request)
    {
        $logo = $this->logoRepository->findWithoutFail($id);

        if (empty($logo)) {
            Flash::error(__('application.logos.not_found'));

            return redirect(route('application.logos.index'));
        }
        $input = $request->all();
        if (array_key_exists('_file_del_', $input)) {
            $imgUrl       = $logo->href;
            $uploadConfig = config('custom.base.upload.logo');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $rootDir      = config('filesystems.disks.' . $driver . '.upload');
            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                $logo->href = null;
                $logo->href->save();
            }
            return response()->json(['message' => '删除成功', 'status' => true]);
        }

        $sValidators = [

        ];

        $validators = [];

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            // 'name'       => '名称',
        ]);

        if ($validator) {
            // 校验
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
        }

        $image = $request->file('href'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.logo');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['href'] = $fullPath;
                $flag          = Storage::disk($driver)->delete($logo->href);

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $logo = $this->logoRepository->update($input, $id);

        Flash::success(__('application.logos.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.logos.index'));
    }

    /**
     * Remove the specified Logo from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->logoRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('application.logos.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $logo = $this->logoRepository->findWithoutFail($id);

        if (empty($logo)) {
            Flash::error(__('application.logos.not_found'));

            return redirect(route('application.logos.index'));
        }

        if ($flag = $this->logoRepository->delete($id)) {

            return response()->json(['message' => __('application.logos.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Logo::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->select('logo_type', '类型')->options(['1' => 'SP', '2' => '组织', '3' => '标签']);
            $form->text('logo_no', '编号');
            $form->text('logotpl', 'logo样式模板');
            $form->image('href', 'logo')->removable();

            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Logo::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('application.logos.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.logos.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.logos.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.logos.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('application.logos.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('application.logos.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('application.logos.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.logos.destroy')) {
                    $actions->disableDelete();
                }
            });

            // 导出按钮
            if (Admin::user()->cannot('application.logos.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.logos.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('logo_type', '类型')->display(function ($val) {
                switch ($val) {
                    case '1':
                        return '<span class="badge bg-green">SP</span>';
                        break;
                    case '2':
                        return '<span class="badge bg-green">组织</span>';
                        break;
                    case '3':
                        return '<span class="badge bg-green">标签</span>';
                        break;
                    default:
                        return '';
                        break;
                }
            });
            $grid->column('logo_no', '编号')->sortable();
            $grid->column('logotpl', 'logo样式模板')->sortable();
            $grid->column('href', 'logo')->image();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->select('logo_type', '类型');

            });
        });
    }
}
